package com.lqk.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lqk.common.utils.PageUtils;
import com.lqk.common.utils.Query;

import com.lqk.mall.product.dao.CategoryDao;
import com.lqk.mall.product.entity.CategoryEntity;
import com.lqk.mall.product.service.CategoryService;

/**
 * @author lqk
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    private CategoryDao categoryDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        // 2. 组装成父子的树形结构
        List<CategoryEntity> list = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(menu -> menu.setChildren(getChildren(menu, categoryEntityList)))
                .sorted(Comparator.comparing(CategoryEntity::getSort,
                        Comparator.nullsLast(Integer::compareTo))
                ).collect(Collectors.toList());

        return list;
    }

    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){

        List<CategoryEntity> categoryEntities = all.stream().filter(categoryEntity ->
                        root.getCatId().equals(categoryEntity.getParentCid()))
                .peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, all)))
                .sorted(Comparator.comparing(CategoryEntity::getSort,
                        Comparator.nullsLast(Integer::compareTo))
                ).collect(Collectors.toList());

        return categoryEntities;
    }

}